<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Drawing on Canvas</title>
    <style>
        .idiom-wrapper {
            width: 100%;
            text-align: center;
        }

        .draw-wrapper {
            display: flex;
            justify-content: space-evenly;
            align-items: center;
        }

        .button-wrapper {
        }

        #canvas {
            width: 600px;
            height: 600px;
            background-color: #abc;
            border: 1px solid black;
        }

        #img-container {
            width: 600px;
            height: 600px;
            border: 1px solid black;
        }

        .color-picker, .width-picker {
            display: inline-flex;
            align-items: center;
        }

        #toolbar {
            display: inline-flex;
            margin-bottom: 10px;
        }

        .color-picker input[type="color"],
        .width-picker input[type="range"] {
            width: 150px;
            height: 30px;
            padding: 0;
            margin-right: 10px;
        }

        .cursor {
            position: absolute;
            border: 1px solid black;
            border-radius: 50%;
            pointer-events: none;
            display: none;
        }
    </style>
</head>
<body>
<div class="idiom-wrapper">
    <span id="idiom-text"></span>
    <button id="new-idiom">新的成语</button>
</div>
<div class="color-picker">
    <label for="colorInput">选择颜色: </label><input type="color" id="colorInput" value="#000000">
</div>
<div class="width-picker">
    <label for="widthInput">笔刷宽度: </label><input type="range" id="widthInput" min="1" max="50" value="2">
</div>
<div id="toolbar">
    <button id="normalBrush">笔刷</button>
    <button id="eraser">橡皮擦</button>
</div>
<div class="draw-wrapper">
    <canvas id="canvas" width="600" height="600"></canvas>
    <div class="button-wrapper">
        <button id="saveBtn">保存</button>
        <button id="clearBtn">清除</button>
    </div>
    <div id="img-container"></div>
</div>
<div class="cursor" id="brushCursor"></div>
<div class="cursor" id="eraserCursor" style="background-color: rgba(255, 255, 255, 0.5);"></div>
<script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const saveBtn = document.getElementById('saveBtn');
    const clearBtn = document.getElementById('clearBtn');
    const newIdiomBtn = document.getElementById('new-idiom');
    const idiomText = document.getElementById('idiom-text');
    const colorInput = document.getElementById('colorInput');
    const widthInput = document.getElementById('widthInput');
    const brushCursor = document.getElementById('brushCursor');
    const eraserCursor = document.getElementById('eraserCursor');

    let isMouseDown = false;
    let isEraser = false;
    let brushColor = colorInput.value;
    let brushWidth = widthInput.value;
    let points = [];

    const setBrush = () => {
        isEraser = false;
        toggleCursorVisibility(brushCursor, eraserCursor);
        ctx.globalCompositeOperation = 'source-over';
    };

    const setEraser = () => {
        isEraser = true;
        toggleCursorVisibility(eraserCursor, brushCursor);
        ctx.globalCompositeOperation = 'destination-out';
    };

    const updateBrushCursor = (size, color) => {
        brushCursor.style.width = `${size}px`;
        brushCursor.style.height = `${size}px`;
        brushCursor.style.backgroundColor = color;
    };

    const updateEraserCursor = (size) => {
        eraserCursor.style.width = `${size}px`;
        eraserCursor.style.height = `${size}px`;
    };

    const toggleCursorVisibility = (showCursor, hideCursor) => {
        showCursor.style.display = 'block';
        hideCursor.style.display = 'none';
        canvas.style.cursor = 'none';
    };

    const getCanvasDataURL = () => canvas.toDataURL();

    const drawSmoothLine = (points) => {
        ctx.beginPath();
        if (points.length < 3) {
            const b = points[0];
            ctx.moveTo(b.x, b.y);
            ctx.lineTo(points[points.length - 1].x, points[points.length - 1].y);
            ctx.stroke();
            ctx.closePath();
            return;
        }
        ctx.moveTo(points[0].x, points[0].y);
        for (let i = 1; i < points.length - 2; i++) {
            const xc = (points[i].x + points[i + 1].x) / 2;
            const yc = (points[i].y + points[i + 1].y) / 2;
            ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc);
        }
        ctx.quadraticCurveTo(
            points[points.length - 2].x,
            points[points.length - 2].y,
            points[points.length - 1].x,
            points[points.length - 1].y
        );
        ctx.lineWidth = brushWidth;
        ctx.strokeStyle = isEraser ? 'rgba(255,255,255,1)' : brushColor;
        ctx.stroke();
        ctx.closePath();
        updateImg();
    };

    const mouseDown = (event) => {
        if (event.button === 0) {
            isMouseDown = true;
            points = [{x: event.offsetX, y: event.offsetY}];
        }
    };

    const mouseUp = () => {
        if (isMouseDown) {
            isMouseDown = false;
            points = [];
        }
    };

    const mouseMove = (event) => {
        if (isMouseDown) {
            const currentPosition = {x: event.offsetX, y: event.offsetY};
            points.push(currentPosition);
            drawSmoothLine(points);
        }
        const cursor = isEraser ? eraserCursor : brushCursor;
        cursor.style.left = `${event.pageX - brushWidth / 2}px`;
        cursor.style.top = `${event.pageY - brushWidth / 2}px`;
    };

    const saveImg = async () => {
        const url = getCanvasDataURL();
        const imgData = url.replace(/^data:image\/png;base64,/, '');
        try {
            const response = await fetch('http://127.0.0.1:3000/save-image', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({imgData})
            });
            console.log(response);
        } catch (error) {
            console.error('Error:', error);
        }
    };

    const updateImg = () => {
        const url = getCanvasDataURL();
        document.getElementById('img-container').innerHTML = `<img src="${url}" alt="" width="600" height="600">`;
    };

    const clearCanvas = () => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        updateImg();
    };

    const getNewIdiom = () => {
        fetch('http://127.0.0.1:3000/get-idiom')
            .then(response => response.json())
            .then(data => {
                idiomText.innerText = data.idiom;
            })
            .catch(error => {
                console.error('Error:', error);
            });
    };

    document.getElementById('normalBrush').addEventListener('click', setBrush);
    document.getElementById('eraser').addEventListener('click', setEraser);
    colorInput.addEventListener('input', (event) => {
        brushColor = event.target.value;
        updateBrushCursor(brushWidth, brushColor);
    });
    widthInput.addEventListener('input', (event) => {
        brushWidth = event.target.value;
        updateBrushCursor(brushWidth, brushColor);
        updateEraserCursor(brushWidth);
    });
    canvas.addEventListener('mousedown', mouseDown);
    canvas.addEventListener('mouseup', mouseUp);
    canvas.addEventListener('mousemove', mouseMove);
    saveBtn.addEventListener('click', saveImg);
    clearBtn.addEventListener('click', clearCanvas);
    newIdiomBtn.addEventListener('click', getNewIdiom);

    getNewIdiom();
    updateBrushCursor(brushWidth, brushColor);
    updateEraserCursor(brushWidth);
</script>
</body>
</html>
